<template>
  <!-- 当ID参数无效时显示此内容 -->
  <div v-if="!id" class="no-param-error">
    <el-result
      icon="error"
      title="无法加载详情"
      sub-title="缺少必要的ID参数或参数无效"
    >
      <template #extra>
        <el-button type="primary" @click="goBack">返回列表</el-button>
      </template>
    </el-result>
  </div>

  <!-- 正常内容在有ID时显示 -->
  <div v-else class="traceability-detail-container">
    <div class="page-header">
      <div class="header-left">
        <h2>溯源详情</h2>
        <el-tag type="info" v-if="detail.traceabilityCode" class="code-tag">{{ detail.traceabilityCode }}</el-tag>
      </div>
      <div class="header-right">
        <el-button type="primary" @click="goBack">
          <el-icon class="el-icon--left"><Back /></el-icon>返回列表
        </el-button>
      </div>
    </div>

    <el-card class="detail-card" v-loading="loading" shadow="hover">
      <template #header>
        <div class="card-header">
          <span class="product-name">{{ detail.productName || '未命名产品' }}</span>
          <el-tag type="success" v-if="detail.traceabilityCode">{{ detail.traceabilityCode }}</el-tag>
        </div>
      </template>

      <div class="detail-content" v-if="!loading && detail.id">
        <el-row :gutter="20">
          <!-- 封面图移到左侧 -->
          <el-col :span="8">
            <div class="image-section">
              <h3>封面图</h3>
              <div class="image-container">
                <el-image 
                  v-if="detail.coverImage" 
                  :src="getImageUrl(detail.coverImage)"
                  fit="cover"
                  :preview-src-list="[getImageUrl(detail.coverImage)]"
                  @error="handleImageError"
                />
                <div v-else class="no-image">
                  <el-icon><Picture /></el-icon>
                  <span>暂无图片</span>
                </div>
              </div>
            </div>
          </el-col>
          
          <!-- 基本信息移到右侧 -->
          <el-col :span="16">
            <div class="detail-section">
              <h3>基本信息</h3>
              <el-descriptions :column="2" border>
                <el-descriptions-item label="溯源码">{{ detail.traceabilityCode || '无' }}</el-descriptions-item>
                <el-descriptions-item label="商品名称">{{ detail.productName || '无' }}</el-descriptions-item>
                <el-descriptions-item label="生产批次">{{ detail.productionBatch || '无' }}</el-descriptions-item>
                <el-descriptions-item label="保质期(天)">{{ detail.shelfLife || '0' }}</el-descriptions-item>
                <el-descriptions-item label="生产许可证号">{{ detail.productionLicenseNumber || '无' }}</el-descriptions-item>
                <el-descriptions-item label="生产企业">{{ detail.productionCompany || '无' }}</el-descriptions-item>
                <el-descriptions-item label="完善度评分">
                  <el-progress 
                    :percentage="detail.completenessScore || 0" 
                    :color="getScoreColor(detail.completenessScore)"
                    :status="getScoreStatus(detail.completenessScore)">
                  </el-progress>
                </el-descriptions-item>
                <el-descriptions-item label="创建时间">{{ formatDateTime(detail.createTime) }}</el-descriptions-item>
                <el-descriptions-item label="更新时间">{{ formatDateTime(detail.updateTime) }}</el-descriptions-item>
              </el-descriptions>
            </div>
          </el-col>
        </el-row>

        <div class="qrcode-section">
          <h3>产品检验报告</h3>
          <div class="inspection-reports-container" v-loading="reportsLoading">
            <div v-if="reports.length > 0" class="reports-list">
              <div v-for="(report, index) in reports" :key="report.id" class="report-item">
                <el-image 
                  :src="getImageUrl(report.reportImagePath)" 
                  fit="cover" 
                  :preview-src-list="reportImageUrls"
                  :initial-index="index"
                  @error="handleImageError"
                  class="report-image"
                >
                  <template #error>
                    <div class="image-error">
                      <el-icon><Picture /></el-icon>
                      <p>加载失败</p>
                    </div>
                  </template>
                </el-image>
                
                <div class="report-actions">
                  <el-tooltip content="删除报告" placement="top">
                    <el-button 
                      type="danger" 
                      :icon="Delete" 
                      circle 
                      size="small" 
                      @click="handleDeleteReport(report.id)"
                    />
                  </el-tooltip>
                  <el-tooltip content="查看时间" placement="top">
                    <span class="report-time">{{ formatDate(report.createTime) }}</span>
                  </el-tooltip>
                </div>
              </div>
            </div>
            
            <div v-else-if="!reportsLoading" class="no-reports">
              <el-empty description="暂无检验报告" :image-size="100">
                <template #description>
                  <p>该商品暂无检验报告，请添加</p>
                </template>
              </el-empty>
            </div>
            
            <div class="upload-container">
              <el-upload
                class="report-uploader"
                action="#"
                :http-request="uploadReport"
                :show-file-list="false"
                :multiple="false"
                accept="image/jpeg,image/jpg,image/png,image/gif,application/pdf"
              >
                <div class="upload-trigger">
                  <el-icon class="upload-icon"><Plus /></el-icon>
                  <span>添加检验报告</span>
                </div>
              </el-upload>
            </div>
          </div>
        </div>
      </div>

      <div v-else-if="!loading && !detail.id" class="no-data">
        <el-empty description="未找到数据">
          <el-button type="primary" @click="goBack">返回列表</el-button>
        </el-empty>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Picture, Download, Refresh, Back, Delete, Plus } from '@element-plus/icons-vue'
import { traceabilityApi } from '@/api/traceability'
import productInspectionApi from '@/api/productInspection'
import QRCode from 'qrcode'

const route = useRoute()
const router = useRouter()
const detail = reactive({})
const loading = ref(true)
const qrcodeRef = ref(null)

// 检验报告相关
const reports = ref([])
const reportsLoading = ref(false)
const reportImageUrls = computed(() => reports.value.map(report => getImageUrl(report.reportImagePath)))

// 获取路由参数中的ID
const id = computed(() => {
  // 优先获取路径参数
  let idValue = route.params.id;
  
  // 确保转换为数字
  if (idValue) {
    try {
      return Number(idValue);
    } catch (e) {
      console.error('ID转换错误:', e);
    }
  }
  
  // 尝试从查询参数获取
  if (route.query.id) {
    try {
      return Number(route.query.id);
    } catch (e) {
      console.error('查询参数ID转换错误:', e);
    }
  }
  
  console.log('找不到有效的ID参数');
  return null;
});

// 获取详情数据
const fetchDetail = async () => {
  if (!id.value && id.value !== 0) {
    console.error('缺少必要参数，ID为空或无效:', id.value);
    ElMessage.error('缺少必要参数');
    loading.value = false;
    handleRouteError();
    return;
  }

  try {
    loading.value = true;
    console.log('开始获取详情数据，ID:', id.value);
    
    // 尝试获取详情数据
    const res = await traceabilityApi.getById(id.value);
    console.log('获取详情数据完整响应:', res);

    if (res && (res.code === 'Success' || res.code === 200 || res.code === 0) && res.data) {
      // 确保所有字段都有默认值
      Object.assign(detail, {
        id: res.data.id || id.value,
        traceabilityCode: res.data.traceabilityCode || '',
        productName: res.data.productName || '未命名产品',
        productionBatch: res.data.productionBatch || '',
        shelfLife: res.data.shelfLife || 0,
        productionLicenseNumber: res.data.productionLicenseNumber || '',
        productionCompany: res.data.productionCompany || '',
        coverImage: res.data.coverImage || '',
        completenessScore: res.data.completenessScore || 0,
        createTime: res.data.createTime || '',
        updateTime: res.data.updateTime || ''
      });
      
      console.log('处理后的详情数据:', detail);
      
      // 渲染二维码
      setTimeout(() => {
        renderQRCode();
      }, 100);

      // 获取检验报告
      await fetchReports(detail.traceabilityCode);
    } else {
      console.error('API返回错误或数据为空:', res);
      ElMessage.error(res?.message || '获取详情数据失败');
      handleRouteError();
    }
  } catch (error) {
    console.error('获取详情数据失败:', error);
    if (error.response) {
      console.error('HTTP错误状态:', error.response.status);
      console.error('错误详情:', error.response.data);
    }
    ElMessage.error('获取详情数据失败: ' + (error.message || '未知错误'));
    handleRouteError();
  } finally {
    loading.value = false;
  }
}

// 格式化日期时间（截止到秒）
const formatDateTime = (dateTimeStr) => {
  if (!dateTimeStr) return '';
  
  try {
    const date = new Date(dateTimeStr);
    if (isNaN(date.getTime())) return dateTimeStr; // 如果无法解析为日期，返回原字符串
    
    // 格式化为 YYYY-MM-DD HH:MM:SS
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');
    
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  } catch (error) {
    console.error('日期格式化错误:', error);
    return dateTimeStr;
  }
}

// 获取图片URL，处理本地URL和CDN URL
const getImageUrl = (url) => {
  if (!url) return '';
  
  // 如果是占位符图片URL，可能是测试数据，直接返回
  if (url.includes('placeholder.com')) {
    return 'https://via.placeholder.com/150?text=示例图片';
  }

  // 已经是完整URL
  if (url.startsWith('http://') || url.startsWith('https://')) {
    return url;
  }

  // 相对URL，添加基础路径
  const baseUrl = 'http://localhost:5203';
  const fullUrl = `${baseUrl}${url.startsWith('/') ? '' : '/'}${url}`;
  return fullUrl;
}

// 处理图片加载错误
const handleImageError = (e) => {
  console.error('图片加载失败:', e)
  e.target.src = 'https://via.placeholder.com/300?text=图片加载失败'
}

// 返回列表页
const goBack = () => {
  console.log('返回列表页');
  // 使用绝对路径
  router.push('/enterprise/traceability');
};

// 根据评分获取颜色
const getScoreColor = (score) => {
  if (!score && score !== 0) return '#909399'
  if (score < 30) return '#F56C6C'
  if (score < 60) return '#E6A23C'
  if (score < 80) return '#67C23A'
  return '#409EFF'
}

// 根据评分获取状态
const getScoreStatus = (score) => {
  if (!score && score !== 0) return ''
  if (score < 30) return 'exception'
  if (score < 60) return 'warning'
  if (score >= 80) return 'success'
  return ''
}

// 生成二维码
const renderQRCode = () => {
  if (!qrcodeRef.value || !detail.id) return
  
  // 生成溯源二维码的URL
  const qrUrl = `http://localhost:5173/traceability/${detail.traceabilityCode || detail.id}`
  
  // 使用qrcode库生成二维码
  QRCode.toCanvas(qrcodeRef.value, qrUrl, {
    width: 200,
    margin: 1,
    color: {
      dark: '#000000',
      light: '#ffffff'
    }
  }, (error) => {
    if (error) {
      console.error('生成二维码失败:', error)
      ElMessage.error('生成二维码失败')
    }
  })
}

// 下载二维码
const downloadQRCode = () => {
  if (!qrcodeRef.value) return
  
  const canvas = qrcodeRef.value
  const url = canvas.toDataURL('image/png')
  const link = document.createElement('a')
  link.download = `溯源码_${detail.traceabilityCode || detail.id}.png`
  link.href = url
  link.click()
}

// 获取检验报告数据
const fetchReports = async (traceabilityCode) => {
  if (!traceabilityCode) return;
  
  try {
    reportsLoading.value = true;
    const res = await productInspectionApi.getByTraceabilityCode(traceabilityCode);
    
    if (res && res.data) {
      reports.value = Array.isArray(res.data) ? res.data : [];
      console.log('获取到检验报告:', reports.value);
    } else {
      reports.value = [];
      console.log('未获取到检验报告或返回格式不正确');
    }
  } catch (error) {
    console.error('获取检验报告失败:', error);
    ElMessage.error('获取检验报告失败');
    reports.value = [];
  } finally {
    reportsLoading.value = false;
  }
};

// 上传检验报告
const uploadReport = async (options) => {
  if (!detail.traceabilityCode) {
    ElMessage.error('无法获取溯源码，无法上传报告');
    return;
  }
  
  try {
    const file = options.file;
    console.log('准备上传文件:', file);
    
    // 文件类型检查
    const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'application/pdf'];
    if (!allowedTypes.includes(file.type)) {
      ElMessage.error('仅支持JPEG, JPG, PNG, GIF和PDF格式');
      return;
    }
    
    // 文件大小检查
    if (file.size > 10 * 1024 * 1024) {
      ElMessage.error('文件大小不能超过10MB');
      return;
    }
    
    // 显示上传中提示
    const loadingMessage = ElMessage({
      type: 'info',
      message: '检验报告上传中...',
      duration: 0
    });
    
    // 调用API上传
    const res = await productInspectionApi.addReport(detail.traceabilityCode, file);
    
    // 关闭上传提示
    loadingMessage.close();
    
    if (res && res.data) {
      ElMessage.success('检验报告上传成功');
      // 重新获取报告列表
      await fetchReports(detail.traceabilityCode);
    } else {
      ElMessage.error('上传失败: ' + (res?.message || '未知错误'));
    }
  } catch (error) {
    console.error('上传检验报告失败:', error);
    ElMessage.error('上传失败: ' + (error.message || '未知错误'));
  }
};

// 删除检验报告
const handleDeleteReport = async (reportId) => {
  try {
    // 确认删除
    await ElMessageBox.confirm('确定要删除这份检验报告吗？此操作不可恢复', '删除确认', {
      confirmButtonText: '确认删除',
      cancelButtonText: '取消',
      type: 'warning'
    });
    
    // 执行删除
    const res = await productInspectionApi.deleteReport(reportId);
    
    if (res && res.code === 0) {
      ElMessage.success('检验报告删除成功');
      // 重新获取报告列表
      await fetchReports(detail.traceabilityCode);
    } else {
      ElMessage.error('删除失败: ' + (res?.message || '未知错误'));
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除检验报告失败:', error);
      ElMessage.error('删除失败: ' + (error.message || '未知错误'));
    }
  }
};

// 日期格式化
const formatDate = (dateStr) => {
  if (!dateStr) return '';
  
  try {
    const date = new Date(dateStr);
    if (isNaN(date.getTime())) return dateStr;
    
    return date.toLocaleString('zh-CN', { 
      year: 'numeric', 
      month: '2-digit', 
      day: '2-digit', 
      hour: '2-digit', 
      minute: '2-digit'
    });
  } catch (e) {
    console.error('日期格式化错误:', e);
    return dateStr;
  }
};

// 处理路由错误
const handleRouteError = () => {
  console.log('尝试从本地存储获取最后访问的记录ID');
  
  // 如果路由参数失效，尝试回到列表页
  ElMessageBox.confirm(
    '无法加载详情数据，可能是记录不存在或已被删除。是否返回列表页？',
    '加载失败',
    {
      confirmButtonText: '返回列表',
      cancelButtonText: '留在当前页面',
      type: 'warning'
    }
  ).then(() => {
    // 使用绝对路径
    router.push('/enterprise/traceability');
  }).catch(() => {
    // 用户选择留在当前页面，不做操作
  });
};

// 组件挂载后获取数据
onMounted(() => {
  console.log('TraceabilityDetail组件挂载, 路由参数:', route.params);
  console.log('当前路径:', route.path);
  console.log('当前完整URL:', window.location.href);
  console.log('计算得到的ID:', id.value);
  
  fetchDetail().catch(err => {
    console.error('获取详情数据出现异常:', err);
    handleRouteError();
  });
});
</script>

<style scoped>
.traceability-detail-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-left h2 {
  margin-bottom: 0;
}

.code-tag {
  margin-left: 10px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.product-name {
  font-size: 18px;
  font-weight: bold;
  color: #303133;
}

.detail-section {
  margin-bottom: 30px;
}

.image-section {
  margin-bottom: 30px;
}

.image-container {
  width: 100%;
  height: 300px;
  display: flex;
  justify-content: center;
  align-items: center;
  border: 1px dashed #dcdfe6;
  border-radius: 6px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  background-color: #f8f9fa;
}

.no-image {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: #909399;
  height: 100%;
  width: 100%;
}

.no-image .el-icon {
  font-size: 64px;
  margin-bottom: 15px;
  color: #c0c4cc;
}

.el-image {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.qrcode-section {
  margin-top: 30px;
  background-color: #f9f9f9;
  padding: 20px;
  border-radius: 6px;
  border: 1px solid #eaeaea;
}

.qrcode-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 15px;
}

.qrcode-box {
  padding: 15px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  margin-bottom: 10px;
}

.qrcode-actions {
  display: flex;
  gap: 10px;
}

.detail-card {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08) !important;
}

.detail-section h3, .image-section h3, .qrcode-section h3 {
  margin-top: 0;
  margin-bottom: 15px;
  font-size: 18px;
  color: #303133;
  font-weight: 500;
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 10px;
}

.no-data {
  padding: 40px 0;
}

.no-param-error {
  padding: 40px 0;
}

.inspection-reports-container {
  margin-top: 15px;
}

.reports-list {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  margin-bottom: 20px;
}

.report-item {
  width: 200px;
  height: 200px;
  border: 1px solid #eaeaea;
  border-radius: 4px;
  overflow: hidden;
  position: relative;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  background-color: #fff;
}

.report-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.report-actions {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: rgba(0, 0, 0, 0.5);
  padding: 5px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.report-time {
  color: #fff;
  font-size: 12px;
}

.image-error {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 100%;
  width: 100%;
  background-color: #f5f7fa;
  color: #909399;
}

.image-error .el-icon {
  font-size: 32px;
  margin-bottom: 10px;
}

.upload-container {
  margin-top: 15px;
}

.report-uploader {
  width: 200px;
  height: 200px;
}

.upload-trigger {
  width: 100%;
  height: 200px;
  border: 1px dashed #d9d9d9;
  border-radius: 4px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  background-color: #fbfdff;
}

.upload-trigger:hover {
  border-color: #409EFF;
  color: #409EFF;
}

.upload-icon {
  font-size: 28px;
  color: #8c939d;
  margin-bottom: 10px;
}

.no-reports {
  margin: 30px 0;
}
</style> 